package com.supporter.sysbench;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author xunaidong
 * @date 2021/8/8
 */
public class ConnectionPoolContext {

    private final static Logger log = LoggerFactory.getLogger(ConnectionPoolContext.class);
    private final GlobalProperties globalProperties;
    private final DruidDataSource dataSource;

    public ConnectionPoolContext(GlobalProperties globalProperties) {
        this.globalProperties = globalProperties;
        dataSource = new DruidDataSource();
        dataSource.setUrl(globalProperties.getData().getJdbcUrl());
        dataSource.setUsername(globalProperties.getData().getUsername());
        dataSource.setPassword(globalProperties.getData().getPassword());
        dataSource.setInitialSize(globalProperties.getThreads());
        dataSource.setMaxActive(globalProperties.getThreads() + 3);
        dataSource.setMinIdle(globalProperties.getThreads());
        dataSource.setDriverClassName(globalProperties.getData().getDriverClassName());
        dataSource.setDefaultAutoCommit(false);
        dataSource.setMaxWait(globalProperties.getData().getConnTimeout());
        dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        try {
            dataSource.addFilters("slf4j");
            dataSource.init();
        } catch (SQLException e) {
            log.info("初始化DataSource连接池失败.", e);
        }
        log.info("初始化DataSource连接池成功,连接数量:{}.", dataSource.getConnectCount());
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public void destroy() {
        if (dataSource != null) {
            dataSource.close();
        }
    }

}
